package com.southpark.system.managers
{
	import com.southpark.system.interfaces.managers.IApplicationManager;
	import com.southpark.system.interfaces.managers.IToolTipManager;
	import com.southpark.system.interfaces.view.IToolTipUI;
	import com.southpark.system.view.toolTips.ToolTipTarget;
	
	import flash.display.DisplayObject;
	import flash.geom.Point;
	import flash.utils.Dictionary;
	
	import mx.core.*;
	import mx.managers.PopUpManager;
	
	
	
	public class ToolTipManager implements IToolTipManager
	{	
		public function ToolTipManager(applicationManager:IApplicationManager)
		{
			this.applicationManager = applicationManager;
		}
		
		private var applicationManager:IApplicationManager;
		

		/**
		 * 
		 */
		private const TOOL_TIP_OFFSET:Number = 10;
		
		private var _toolTipUI:IToolTipUI;
		public function get toolTipUI():IToolTipUI
		{
			return _toolTipUI;
		}
		
		private var toolTipDictionary:Dictionary = new Dictionary();
		private function getToolTipUI(toolTipInterface:Class):IToolTipUI
		{	
		 	if (toolTipDictionary[toolTipInterface])
		 	{
		 		return toolTipDictionary[toolTipInterface] as IToolTipUI;
		 	};
		 	
		 	var toolTipClass:Class = applicationManager.assetManager.getAsset(toolTipInterface);
		 	if (!toolTipClass) 
		 	{
		 		return null;
		 	};
		 	
		 	var toolTipUI:IToolTipUI = new toolTipClass();
		 	
		 	toolTipUI.toolTipManager = this;
		 	toolTipDictionary[toolTipInterface] = toolTipUI;
		 	
		 	return toolTipUI;
		}

		private function get background():DisplayObject
		{
			return applicationManager.background as DisplayObject;
		}
		
		public function showToolTip(toolTipTarget:ToolTipTarget,toolTipInterface:Class,point:Point,data:Object):void
		{
			hideToolTip();
			
			_toolTipUI = getToolTipUI(toolTipInterface);
			if (!_toolTipUI) return;
			
			mx.managers.PopUpManager.addPopUp(IFlexDisplayObject(_toolTipUI),background);
						
			_toolTipUI.toolTipTarget = toolTipTarget;
			_toolTipUI.data = data;
			
			var toolTipX:Number = point.x - _toolTipUI.width + TOOL_TIP_OFFSET;
			if (toolTipX < 0) 
			{
				toolTipX = point.x + toolTipTarget.origin.width - TOOL_TIP_OFFSET;
			};
			
			var toolTipY:Number = point.y;
			if (toolTipY + _toolTipUI.height > background.height)
			{
				toolTipY = background.height - _toolTipUI.height;
			};
			
			_toolTipUI.x = toolTipX;
			_toolTipUI.y = toolTipY;
		}
		
		public function hideToolTip():void
		{
			if (_toolTipUI)
			{
				mx.managers.PopUpManager.removePopUp(IFlexDisplayObject(_toolTipUI));
				_toolTipUI = null;
			};
		}
		
	}
}